package com.codebo.homiematch.endpoint;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codebo.homiematch.config.SpringBeanContext;
import com.codebo.homiematch.model.dto.ChatDTO;
import com.codebo.homiematch.model.entity.User;
import com.codebo.homiematch.model.vo.ChatVO;
import com.codebo.homiematch.service.ChatService;
import com.codebo.homiematch.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chat/public")
@Component
public class ChatEndpoint
{

    //    @Resource
//    private ChatService chatService;
//    @Resource
//    private UserService userService;
    private static final Set<Session> sessions = ConcurrentHashMap.newKeySet();

    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("WebSocket 连接已经建立。");
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException
    {
        ChatDTO chatDTO = JSONUtil.toBean(message, ChatDTO.class);
        ChatService chatService = SpringBeanContext.getContext().getBean(ChatService.class);
        UserService userService = SpringBeanContext.getContext().getBean(UserService.class);
        ObjectMapper objectMapper = SpringBeanContext.getContext().getBean(ObjectMapper.class);
        ChatVO chatVO = chatService.saveChat(chatDTO);
        for (Session session1 : sessions)
        {
            session1.getBasicRemote().sendText(objectMapper.writeValueAsString(chatVO));
//            if(session1!=session)
//            {
//                session1.getBasicRemote().sendText(JSONUtil.toJsonStr(chatVO));
//            }

        }
    }

    @OnClose
    public void onClose()
    {
        System.out.println("WebSocket 连接已经关闭。");
    }

    @OnError
    public void onError(Throwable t)
    {
        System.out.println("WebSocket 连接出现错误：" + t.getMessage());
    }
}
